package com.cskaoyan.market.controller;

import com.cskaoyan.market.db.domain.MarketAdmin;
import com.cskaoyan.market.group.Login;
import com.cskaoyan.market.service.AdminAuthService;
import com.cskaoyan.market.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lixianbiao
 * @since 2024/06/28 18:42
 */
@RestController
@RequestMapping("admin/auth")
public class AdminAuthController {
    @Autowired
    private AdminAuthService adminAuthService;

    @PostMapping("login")
    public Object login(@Validated({Login.class}) @RequestBody MarketAdmin marketAdmin, HttpServletRequest request){
        MarketAdmin admin = adminAuthService.login(marketAdmin);
        if(admin!=null){
            HttpSession session = request.getSession();
            session.setAttribute("admin",admin);
            Map<String, Object> data = new HashMap<>();
            Map<String, String> adminInfo = new HashMap<>();
            adminInfo.put("nickName", admin.getUsername());
            adminInfo.put("avatar", admin.getAvatar());
            data.put("adminInfo", adminInfo);
            //把session的编号返回给前端，它需要
            data.put("token", session.getId());
            Object ok = ResponseUtil.ok(data);
            return ok;
        }else {
            Object fail = ResponseUtil.fail(402, "用户帐号或密码不正确");
            return fail;
        }
    }

    @GetMapping("info")
    public Object info(HttpServletRequest request, @SessionAttribute("admin") MarketAdmin admin){
        Map<String, Object> data = new HashMap<>();
        data.put("roles", Arrays.asList("超级管理员"));
        data.put("name", admin.getUsername());
        data.put("avatar", admin.getAvatar());
        data.put("perms", Arrays.asList("*"));
        Object ok = ResponseUtil.ok(data);
        return ok;
    }

    @PostMapping("logout")
    public Object logout(HttpSession session){
        session.invalidate();
        Object result = ResponseUtil.ok();
        return result;
    }
}